package org.dq.base.page.impl;
import java.util.List;

import org.dq.base.page.Page;
import org.dq.base.page.PageEngine;
import org.dq.base.page.PageException;
import org.dq.base.page.PageParam;


public class PageImpl implements Page {
	
	
	private static final long serialVersionUID = 1L;
	private int curr;
	private int total;
	private int pgTotal;
	private int rows;
	
	private List<?> recList;
	
	public PageImpl(PageEngine<?> engine,PageParam pageParam)throws PageException{
		try {
			this.rows=Integer.parseInt(pageParam.getRows());
		} catch (NumberFormatException e1) {
			//e1.printStackTrace();
			this.rows=Page.ROWS_DEFAULT;
		}
		if(this.rows<1){
			throw new PageException("每页记录数不允许少于1。");
		}
		
		
		try {
			total=engine.getTotal();
			
			if(total<1){
				pgTotal=1;
			}else{
				if(total%this.rows==0){
					pgTotal=total/this.rows;
				}else{
					pgTotal=total/this.rows+1;
				}
			}
			
			try {
				curr=Integer.parseInt(pageParam.getPage());
			} catch (NumberFormatException e) {
				curr=Page.CURR_DEFAULT;
			}
			
			if(curr<getFirst()){
				curr=getFirst();
			}else if(curr>getLast()){
				curr=getLast();
			}
			
			
			recList=engine.getData((curr-1)*this.rows,curr*this.rows);
			
		} catch (Exception e) {
			throw new PageException("创建Page对象失败。",e);
		}
		
	}
	
	
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getFirst()
	 */
	@Override
	public int getFirst(){
		return 1;
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getPrior()
	 */
	@Override
	public int getPrior(){
		return getCurr()-1<getFirst()?getFirst():(getCurr()-1);
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getNext()
	 */
	@Override
	public int getNext(){
		return getCurr()+1>getLast()?getLast():(getCurr()+1);
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getLast()
	 */
	@Override
	public int getLast(){
		return pgTotal;
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getCurr()
	 */
	@Override
	public int getCurr(){
		return curr;
	}
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getPgTotal()
	 */
	@Override
	public int getPgTotal(){
		return pgTotal;
	}
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getTotal()
	 */
	@Override
	public int getTotal(){
		return total;
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getCurrRows()
	 */
	@Override
	public int getCurrRows(){
		return recList.size();
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getRows()
	 */
	@Override
	public int getRows(){
		return rows;
	}
	
	/* (non-Javadoc)
	 * @see com.xdq.base.page.impl.Page#getData()
	 */
	@Override
	public List<?> getRecList(){
		return recList;
	}
	
	
	

}
